import React, { useState, useEffect, Fragment } from 'react';
import { Row, Col, Radio, DatePicker, Spin, Tooltip } from 'antd';
import { connect } from 'dva';
import moment from 'moment';

import ColorBlocks from '@/components/ColorBlocks/ColorBlocks';
import ModuleCard from '@/components/Card/ModuleCard';
import BasicTitle from '@/components/Card/BasicTitle';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ConnectState from '@/models/connect';
import MyIcon from '@/components/MyIcon';
import HomeBaseChart from '@/components/Chart/BasicChart';
import { EnterpriseCfg } from './config/overview';
import classNames from 'classnames/bind';

import styles from './home.less';

const cx = classNames.bind(styles);

const { RangePicker } = DatePicker;

const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const formatterLabelx = (text, item, index) => {
  return text.length > 4 ? text.substring(0, 4) + '...' : text;
};
const countDays = value => moment().subtract(value, 'days').format('YYYY-MM-DD') + ' 00:00:00';
const typeArray = [
  {
    className: '',
    valueShow: 0,
    name: '浏览量(PV)',
    value: 'pv',
    detail: '用户每打开一个页面，记录一次',
  },
  {
    className: '',
    valueShow: 0,
    name: '访客数(UV)',
    value: 'uv',
    detail: '一天内同一访客访问多次，记为1次',
  },
  { className: '', valueShow: 0, name: 'IP数', value: 'ipCount', detail: '一天内的独立访问IP数' },
];
const TYPE_NAME = {
  pv: '浏览量',
  uv: '访客数',
  ipCount: 'IP数',
};

function disabledDate(current) {
  // Can not select days before 60天前面
  return (
    (current && current < moment().subtract(60, 'days').endOf('day')) ||
    (current && current > moment().endOf('day'))
  );
}

const DataOverview = props => {
  const [recruitTotalData, setRecruitTotalData] = useState(EnterpriseCfg);
  const [radioValue, setRadioValue] = useState('30');
  const [radioTypeValue, setRadioTypeValue] = useState('pv');
  const [endTime, setEndTime] = useState(moment().format(DATE_FORMAT));
  const [startTime, setStartTime] = useState(moment().subtract(30, 'days').format(DATE_FORMAT));

  const { dispatch, homeIndex, chartLoading } = props;
  const {
    homeDataTotal = {},
    visitInfo = [],
    visitDetail = {},
    policyTop = [],
    policyType = [],
    noticeTop = [],
    noticeType = [],
    comInfopType = [],
    comInfopArea = [],
    projectList = [],
    projectProgressList = [],
    userAvator = {},
  } = homeIndex;

  const handleRadioChange = event => {
    const value = event.target.value;

    setRadioValue(value);

    setStartTime(countDays(parseInt(value)));
    setEndTime(moment().format(DATE_FORMAT));
  };
  const handleRadioTypeChange = event => {
    const value = event.target.value;
    setRadioTypeValue(value);
  };

  const changeRangeDate = (dates: Date[]) => {
    if (dates.length > 0) {
      setStartTime(moment(dates[0]).format('YYYY-MM-DD') + ' 00:00:00');
      setEndTime(moment(dates[1]).format('YYYY-MM-DD') + ' 23:59:59');
      setRadioValue('');
    }
  };

  useEffect(() => {
    const nData = recruitTotalData.map(item => ({
      ...item,
      desc: homeDataTotal ? item.key && homeDataTotal[`${item.key}`] : '',
    }));
    setRecruitTotalData(nData);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [homeDataTotal]);

  useEffect(() => {
    dispatch({ type: 'homeIndex/queryDataTotal' });
    dispatch({ type: 'homeIndex/queryPolicyTop' });
    dispatch({ type: 'homeIndex/queryPolicyType' });
    dispatch({ type: 'homeIndex/queryNoticeTop' });
    dispatch({ type: 'homeIndex/queryNoticeType' });
    dispatch({ type: 'homeIndex/queryComInfop', payload: { type: 1 } });
    dispatch({ type: 'homeIndex/queryComInfop', payload: { type: 2 } });
    dispatch({ type: 'homeIndex/queryProjectList' });
    dispatch({ type: 'homeIndex/queryProjectProgressList' });
    dispatch({ type: 'homeIndex/queryUserAvatorAsync' });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    refreshCharts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [startTime, endTime]);

  const refreshCharts = () => {
    dispatch({ type: 'homeIndex/queryVisitInfo', payload: { startTime, endTime } });
  };

  const WrappedRecruitOverview = ModuleCard(ColorBlocks);
  // const RecruitChart = ModuleCard(BasicColumn);
  // const JobChart = ModuleCard(BasicColumn);
  // const MatchChart = ModuleCard(RingDiagram);
  // const detail = visitInfo[visitInfo.length - 1] || {};
  const typeArrayShow = typeArray.map(item => {
    item.className = cx(styles['type-item'], {
      selected: radioTypeValue === item.value,
    });
    item.valueShow = visitDetail[item.value] || 0;
    return item;
  });
  let genders;
  const originGender = userAvator.genders || [];
  if (originGender.length > 0) {
    const total = originGender[0].value + originGender[1].value;
    const gendersArray = originGender.map(item => {
      item.rate = Number((item.value / total).toFixed(2));
      // item.rate = 0.5
      item.age = '占比';
      return item;
    });
    genders = gendersArray;
    // const ds = new DataSet();
    // genders = ds
    //   .createView()
    //   .source(gendersArray)
    //   .transform({
    //     type: "percent",
    //     field: "value",
    //     // 统计销量
    //     dimension: "name",
    //     // 每年的占比
    //     groupBy: ["age"],
    //     // 以不同产品类别为分组
    //     as: "percent"
    //   });
  }

  return (
    <PageHeaderWrapper>
      <div className={styles.detail}>
        <Row>
          <WrappedRecruitOverview
            cardTitle="企链保数据概览"
            showHighLightIcon={true}
            containerStyle={{ width: '100%' }}
            containerClassName={styles.totalOverview}
            number={5}
            cfgList={recruitTotalData}
          />
        </Row>

        <Spin spinning={chartLoading} delay={300}>
          <div>
            <Row gutter={24}>
              <Col span={16} style={{ position: 'relative' }}>
                <BasicTitle
                  cardTitle="用户趋势分析"
                  showHighLightIcon={true}
                  containerStyle={{ height: '400px' }}
                >
                  <Fragment>
                    <div className={styles['time-parent']}>
                      <Radio.Group onChange={handleRadioChange} value={radioValue}>
                        <Radio.Button value="7">最近7天</Radio.Button>
                        <Radio.Button value="30">最近30天</Radio.Button>
                      </Radio.Group>
                      <RangePicker
                        style={{ marginLeft: '30px' }}
                        allowClear={false}
                        disabledDate={disabledDate}
                        value={[moment(startTime), moment(endTime)]}
                        onChange={changeRangeDate}
                      />
                    </div>
                    <div>
                      <Radio.Group
                        className={styles['type-select']}
                        onChange={handleRadioTypeChange}
                        value={radioTypeValue}
                      >
                        {typeArrayShow.map(item => (
                          <Fragment>
                            <Radio className={item.className} value={item.value}>
                              <span style={{ fontSize: '12px', color: '#5C6F88' }}>
                                {item.name}{' '}
                                <Tooltip title={item.detail}>
                                  <MyIcon
                                    style={{ fontSize: '13px', color: '#DEE6F0' }}
                                    type="iconwenhao"
                                  ></MyIcon>
                                </Tooltip>
                              </span>
                              <div className={styles['value-part']}>{item.valueShow}</div>
                            </Radio>
                          </Fragment>
                        ))}
                      </Radio.Group>
                    </div>
                    <HomeBaseChart
                      data={visitInfo}
                      typeGeom="line"
                      colorGeo={['stDate', ['#0090FB']]}
                      axisY={radioTypeValue}
                      axisX="stDate"
                      scale={{
                        stDate: {
                          type: 'time',
                          tickCount: 7,
                        },
                      }}
                      useHtml={true}
                      htmlContent={(title, items) => {
                        const data = items[0] || {
                          point: { _origin: { ipCount: 0, pv: 0, uv: 0 } },
                        };
                        const originData = data.point._origin;
                        const value = `${TYPE_NAME[radioTypeValue]}: ${originData[radioTypeValue]}`;
                        return `<div class="g2-tooltip" style='font-size:12px;position:absolute;padding:13px 8px 8px;min-width:128px;box-sizing:border-box;border-radius:4px;background:rgba(255,255,255,0.96);box-shadow:rgb(174, 174, 174) 0px 0px 10px;'>
                              <div class="g2-tooltip-title">${title} </div><ul><li>${value}</li></ul></div>`;
                      }}
                      gridY={{}}
                      lineX={{}}
                      tickLineX={{}}
                      labelX={{
                        textStyle: {
                          textAlign: 'center',
                        },
                      }}
                      labelY={{}}
                      height={260}
                      // padding={[20, 20, 40, 30]}
                      padding={['10%', '5%', '15%', '10%']}
                    />
                  </Fragment>
                </BasicTitle>
              </Col>
              <Col span={8}>
                <BasicTitle
                  cardTitle="用户画像"
                  showHighLightIcon={true}
                  containerStyle={{ paddingBottom: 0, height: '400px' }}
                >
                  <Fragment>
                    <HomeBaseChart
                      subTitle="年龄分布"
                      data={userAvator.ages || []}
                      visibleY={false}
                      lineX={{}}
                      labelX={{}}
                      colorGeo={['name', ['l (90) 0:rgba(0,199,253, 1) 1:rgba(50,172,255, 1)']]}
                      axisX="name"
                      axisY="rate"
                      sizeGeom={20}
                      scale={{
                        rate: {
                          min: 0,
                          formatter(val) {
                            return (val * 100).toFixed(1) + '%';
                          },
                        },
                      }}
                      height={165}
                      padding={[20, 30, 30, 0]}
                      // padding={['10%', '5%', '15%', '5%']}
                    />
                    <div className={styles.subTitleParent}>
                      <div className={styles.subtitleSpe}>性别分布</div>
                      <HomeBaseChart
                        data={genders}
                        transpose
                        typeGeom="intervalStack"
                        colorGeo={['name', ['#0090FB', '#FF8C65']]}
                        scale={{
                          rate: {
                            min: 0,
                            formatter(val) {
                              return (val * 100).toFixed(1) + '%';
                            },
                          },
                        }}
                        showLegend
                        positionLegend="top-right"
                        legendName="name"
                        legendOffsetY={-30}
                        axisX="age"
                        axisY="rate"
                        height={137}
                        padding={[60, 20, 0, 0]}
                        // padding={['10%', '5%', '15%', '5%']}
                      />
                    </div>
                  </Fragment>
                </BasicTitle>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={12}>
                <BasicTitle cardTitle="公告数据" showHighLightIcon={true}>
                  <Row gutter={0}>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="公告类型"
                        data={noticeType}
                        showLegend
                        positionLegend="right-bottom"
                        typeGeom="intervalStack"
                        positionGeom="count"
                        showTitle={true}
                        tooltipGeom={[
                          'count*rate',
                          (count, rate) => {
                            // array
                            return {
                              name: count + '条',
                              value: `占比${(rate * 100).toFixed(1)}%`,
                            };
                          },
                        ]}
                        tooltipTitle="cnName"
                        type="theta"
                        axisX="cnName"
                        axisY="rate"
                        height={260}
                        // padding={[20, 80, 40, 30]}
                        padding={['10%', '35%', '15%', '5%']}
                      />
                    </Col>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="公告发布数量TOP5"
                        data={noticeTop.slice(0, 5)}
                        innerRadius={0}
                        type="rect"
                        colorGeo={[
                          'publisher',
                          ['l (180) 0:rgba(0,199,253, 1) 1:rgba(50,172,255, 1)'],
                        ]}
                        axisX="publisher"
                        axisY="count"
                        showLabel="count"
                        visibleY={false}
                        transpose
                        labelX={{
                          formatter: formatterLabelx,
                        }}
                        height={260}
                        padding={[20, 30, 40, 90]}
                        // padding={['10%', '10%', '15%', '30%']}
                      />
                    </Col>
                  </Row>
                </BasicTitle>
              </Col>
              <Col span={12}>
                <BasicTitle cardTitle="政策数据" showHighLightIcon={true}>
                  <Row gutter={0}>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="政策类型"
                        data={policyType}
                        innerRadius={0}
                        showLegend
                        positionLegend="right-bottom"
                        typeGeom="intervalStack"
                        positionGeom="count"
                        showTitle={true}
                        tooltipGeom={[
                          'count*rate',
                          (count, rate) => {
                            // array
                            return {
                              name: count + '条',
                              value: `占比${(rate * 100).toFixed(1)}%`,
                            };
                          },
                        ]}
                        tooltipTitle="type"
                        type="theta"
                        axisX="type"
                        axisY="count"
                        height={260}
                        // padding={[20, 80, 40, 30]}
                        padding={['10%', '35%', '15%', '10%']}
                      />
                    </Col>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="政策发布数量TOP5"
                        data={policyTop.slice(0, 5)}
                        innerRadius={0}
                        type="rect"
                        colorGeo={[
                          'publisher',
                          ['l (180) 0:rgba(0,199,253, 1) 1:rgba(50,172,255, 1)'],
                        ]}
                        axisX="publisher"
                        axisY="count"
                        showLabel="count"
                        visibleY={false}
                        transpose
                        labelX={{
                          formatter: formatterLabelx,
                        }}
                        height={260}
                        padding={[20, 30, 40, 90]}
                        // padding={['10%', '10%', '15%', '30%']}
                      />
                    </Col>
                  </Row>
                </BasicTitle>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={12}>
                <BasicTitle cardTitle="企业数据" showHighLightIcon={true}>
                  <Row gutter={0}>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="企业类型"
                        data={comInfopType}
                        type="rect"
                        axisX="name"
                        axisY="count"
                        linearColor
                        visibleY={false}
                        sizeGeom={20}
                        labelX={{
                          formatter: formatterLabelx,
                        }}
                        height={260}
                        padding={[20, 30, 40, 20]}
                        // padding={['10%', '10%', '15%', '10%']}
                      />
                    </Col>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="所在园区"
                        data={comInfopArea}
                        innerRadius={0.7}
                        showLegend
                        positionLegend="right-bottom"
                        typeGeom="intervalStack"
                        positionGeom="count"
                        showTitle={true}
                        tooltipGeom={[
                          'count*rate',
                          (count, rate) => {
                            // array
                            return {
                              name: count + '家',
                              value: `占比${(rate * 100).toFixed(1)}%`,
                            };
                          },
                        ]}
                        tooltipTitle="name"
                        type="theta"
                        axisX="name"
                        axisY="count"
                        height={260}
                        // padding={[20, 85, 40, 30]}
                        padding={['10%', '35%', '15%', '10%']}
                      />
                    </Col>
                  </Row>
                </BasicTitle>
              </Col>
              <Col span={12}>
                <BasicTitle cardTitle="招商数据" showHighLightIcon={true}>
                  <Row gutter={0}>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="各招商平台项目比例"
                        data={projectList}
                        typeGeom="intervalStack"
                        positionGeom="value"
                        type="theta"
                        showTitle={true}
                        tooltipGeom={[
                          'value*rate',
                          (value, rate) => {
                            // array
                            console.log(value, rate, '##########3');
                            return {
                              name: value + '个',
                              value: `占比${(rate * 100).toFixed(1)}%`,
                            };
                          },
                        ]}
                        tooltipTitle="name"
                        axisX="name"
                        axisY="value"
                        height={260}
                        // padding={[20, 40, 40, 30]}
                        padding={['10%', '10%', '15%', '10%']}
                      />
                    </Col>
                    <Col span={12}>
                      <HomeBaseChart
                        subTitle="项目推进进度"
                        data={projectProgressList}
                        innerRadius={0}
                        type="rect"
                        axisX="name"
                        axisY="value"
                        showLabel="value"
                        sizeGeom={20}
                        linearColor
                        visibleY={false}
                        transpose
                        labelX={{
                          formatter: formatterLabelx,
                        }}
                        height={260}
                        padding={[20, 30, 60, 90]}
                        // padding={['10%', '10%', '15%', '30%']}
                      />
                    </Col>
                  </Row>
                </BasicTitle>
              </Col>
            </Row>
          </div>
        </Spin>
      </div>
    </PageHeaderWrapper>
  );
};

const mapStateToProps = ({ homeIndex, loading }: ConnectState) => {
  return { homeIndex, chartLoading: loading.global };
};

export default connect(mapStateToProps)(DataOverview);
